package com.egao.common.module.recommendation.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.component.minio.config.MinioBucket;
import com.egao.common.core.exception.ParameterException;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.manage.CommonRefService;
import com.egao.common.module.recommendation.entity.GraduateEmploymentCertification;
import com.egao.common.module.recommendation.entity.vo.CivilServiceApplicationRecommendationVo;
import com.egao.common.module.recommendation.service.ICivilServiceApplicationRecommendationService;
import com.egao.common.module.recommendation.constants.RecommendationConstants;
import com.egao.common.module.recommendation.entity.CivilServiceApplicationRecommendation;
import com.egao.common.module.recommendation.entity.vo.RecommendationAuditParam;
import com.egao.common.module.recommendation.entity.vo.RecommendationListVo;
import com.egao.common.module.recommendation.mapper.CivilServiceApplicationRecommendationMapper;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.entity.StudentInfo;
import com.egao.common.module.student.mapper.StudentInfoMapper;
import com.egao.common.module.student.mapper.StudentMapper;
import com.egao.common.module.system.constants.DictConstants;
import com.egao.common.module.system.constants.UserConstants;
import com.egao.common.module.system.entity.College;
import com.egao.common.module.system.entity.Major;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.mapper.CollegeMapper;
import com.egao.common.module.system.mapper.MajorMapper;
import com.egao.common.module.system.mapper.UserMapper;
import com.egao.common.module.system.service.impl.DictServiceImpl;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.*;
import com.itextpdf.text.Utilities;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import java.nio.file.Files;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 公务员考试报名推荐表（应届生版） 服务实现类
 *
 * @author shu
 */
@Service
public class CivilServiceApplicationRecommendationServiceImpl extends ServiceImpl<CivilServiceApplicationRecommendationMapper, CivilServiceApplicationRecommendation> implements ICivilServiceApplicationRecommendationService {
    private DictServiceImpl dictService;
    private StudentMapper studentMapper;
    private UserMapper userMapper;
    private CommonRefService refService;
    private CollegeMapper collegeMapper;
    private MajorMapper majorMapper;
    private StudentInfoMapper studentInfoMapper;

    @Value("${minio.recmdDir}")
    private String recmdDir;
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${pdf.font}")
    private String pdfFont;
    @Value("${pdf.picture}")
    private String pdfPicture;
    @Autowired
    public CivilServiceApplicationRecommendationServiceImpl(DictServiceImpl dictService, ResourceLoader resourceLoader, StudentMapper studentMapper, UserMapper userMapper, CommonRefService refService, CollegeMapper collegeMapper, MajorMapper majorMapper, StudentInfoMapper studentInfoMapper) {
        this.dictService = dictService;
        this.studentMapper = studentMapper;
        this.userMapper = userMapper;
        this.refService = refService;
        this.collegeMapper = collegeMapper;
        this.majorMapper = majorMapper;
        this.studentInfoMapper = studentInfoMapper;
    }

    @Override
    public PageResult<RecommendationListVo> list(PageParam<CivilServiceApplicationRecommendation> page) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User curUser = (User) authentication.getPrincipal();
        QueryWrapper<CivilServiceApplicationRecommendation> wrapper = new QueryWrapper<>();
        wrapper.ge(page.getPageData().get("beginDate") != null, "update_time", page.getPageData().get("beginDate"));
        wrapper.lt(page.getPageData().get("endDate") != null, "update_time", page.getPageData().get("endDate"));
        wrapper.eq(page.getPageData().get("status") != null, "status", page.getPageData().get("status"));
        // 学生只能查看自己的记录
        Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("user_id", curUser.getUserId()));
        if (student != null) {
            wrapper.eq("user_id", student.getUserId());
            return new PageResult<>(models2vos(this.page(page, wrapper).getRecords()), page.getTotal());
        }
        //教师逻辑，仅查询本院学生
        User teacher = userMapper.selectById(curUser.getUserId());
        wrapper.eq(curUser.getDegreeScope() != null && !UserConstants.DEGREE_SCOPE_ALL.equals(curUser.getDegreeScope()),
                "degree", curUser.getDegreeScope());
        wrapper.eq("college_code", teacher.getCollegeCode());
        wrapper.ne("status", RecommendationConstants.RECOMMENDATION_STATUS_INIT);
        //处理筛选条件
        if (page.getPageData().get("con") != null && StrUtil.isNotBlank((String) page.getPageData().get("con"))) {
            wrapper.and(w -> w.like("xh", page.getPageData().get("con")).or().like("xm", page.getPageData().get("con")));
        }
        return new PageResult<>(models2vos(this.page(page, wrapper).getRecords()), page.getTotal());
    }

    public List<RecommendationListVo> models2vos(List<CivilServiceApplicationRecommendation> models) {
        LinkedList<RecommendationListVo> vos = new LinkedList<>();
        List<String> codes = new LinkedList<>();
        models.forEach(model -> {
            RecommendationListVo vo = new RecommendationListVo();
            BeanUtils.copyProperties(model, vo);
            if(StrUtil.isNotBlank(model.getCollegeCode())&&!codes.contains(model.getCollegeCode())){
                codes.add(model.getCollegeCode());
            }
            vos.add(vo);
        });
        Map<String, College> map = refService.refCollege(codes);
        vos.forEach(vo -> {
            if (map.get(vo.getCollegeCode()) != null) {
                vo.setCollegeName(map.get(vo.getCollegeCode()).getName());
            }
        });
        return vos;
    }

    @Override
    public JsonResult read(Integer id) {//非学生型单条查询
        if (id == null) {
            throw new ParameterException("参数对象为空");
        }

        CivilServiceApplicationRecommendation model = baseMapper.selectById(id);
        CivilServiceApplicationRecommendationVo vo = new CivilServiceApplicationRecommendationVo();
        BeanUtils.copyProperties(model, vo);
        //拿出之前前端输入的内容
        Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("user_id", model.getUserId()));
        College college = collegeMapper.selectOne(new QueryWrapper<College>().eq("code", student.getCollegeCode()));
        StudentInfo studentInfo = studentInfoMapper.selectOne(new QueryWrapper<StudentInfo>().eq("user_id", model.getUserId()));
        Major major = majorMapper.selectOne(new QueryWrapper<Major>().eq("code", student.getMajorCode()));
        //所有从后端拿的都在这里
        //单用户所以不做多的事情
        String label;
        vo.setSfzhm(student.getSfzhm());//身份证号码
        String collegeName = college.getName();
        if (collegeName.endsWith("研")) {
            // 如果以 "研" 结尾，去掉 "研"
            vo.setCollegeName(collegeName.substring(0, collegeName.length() - 1));
        } else {
            // 否则直接设置毕业院校名称
            vo.setCollegeName(collegeName);
        }
        vo.setMobile(student.getMobile());
        vo.setEmail(student.getEmail());
        vo.setXm(student.getXm());//姓名
        vo.setXb(dictService.cacheLabel(DictConstants.TYPE_XB, student.getXb()));//性别
        vo.setMz(dictService.cacheLabel(DictConstants.TYPE_MZ, student.getMz()));//民族
        vo.setCsrq(student.getCsrq());//出生日期
        //籍贯要自己填
        vo.setSysf(student.getSysf());//生源省份
        vo.setHyzk(dictService.cacheLabel(DictConstants.TYPE_HYZK, studentInfo.getHyzk()));//婚姻状况，属附加
        vo.setZzmm(dictService.cacheLabel(DictConstants.TYPE_ZZMM, student.getZzmm()));//政治面貌
        vo.setMajorDegree(major.getName() + dictService.cacheLabel(DictConstants.TYPE_XW, student.getDegree()));//专业
        vo.setSyszd(dictService.cacheLabel(DictConstants.TYPE_SYSZD, student.getSyszd()));
        vo.setXl(dictService.cacheLabel(DictConstants.TYPE_XL, student.getXl()));
        vo.setMajorName(major.getName());
        return JsonResult.ok().setData(vo);
    }

    @Override
    public JsonResult read() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User curUser = (User) authentication.getPrincipal();
        CivilServiceApplicationRecommendation model = baseMapper.selectOne(new QueryWrapper<CivilServiceApplicationRecommendation>().eq("user_id", curUser.getUserId()));
        if (model==null) {
            CivilServiceApplicationRecommendationVo vo  = new CivilServiceApplicationRecommendationVo();
            //拿出之前前端输入的内容
            Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("user_id", curUser.getUserId()));
            College college = collegeMapper.selectOne(new QueryWrapper<College>().eq("code", student.getCollegeCode()));
            StudentInfo studentInfo = studentInfoMapper.selectOne(new QueryWrapper<StudentInfo>().eq("user_id", curUser.getUserId()));
            Major major = majorMapper.selectOne(new QueryWrapper<Major>().eq("code", student.getMajorCode()));
            //所有从后端拿的都在这里
            vo.setDegree(student.getDegree());
            vo.setSfzhm(student.getSfzhm());//身份证号码
            String collegeName = college.getName();
            if (collegeName.endsWith("研")) {
                // 如果以 "研" 结尾，去掉 "研"
                vo.setCollegeName(collegeName.substring(0, collegeName.length() - 1));
            } else {
                // 否则直接设置毕业院校名称
                vo.setCollegeName(collegeName);
            }
            vo.setMobile(student.getMobile());
            vo.setEmail(student.getEmail());
            vo.setXm(student.getXm());//姓名
            vo.setXb(dictService.cacheLabel(DictConstants.TYPE_XB, student.getXb()));//性别
            vo.setMz(dictService.cacheLabel(DictConstants.TYPE_MZ, student.getMz()));//民族
            vo.setCsrq(student.getCsrq());//出生日期
            //籍贯要自己填
            vo.setSysf(student.getSysf());//生源省份
            vo.setHyzk(dictService.cacheLabel(DictConstants.TYPE_HYZK, studentInfo.getHyzk()));//婚姻状况，属附加
            vo.setZzmm(dictService.cacheLabel(DictConstants.TYPE_ZZMM, student.getZzmm()));//政治面貌
            vo.setMajorDegree(major.getName() + dictService.cacheLabel(DictConstants.TYPE_XW, student.getDegree()));//专业
            vo.setSyszd(dictService.cacheLabel(DictConstants.TYPE_SYSZD, student.getSyszd()));
            vo.setXl(dictService.cacheLabel(DictConstants.TYPE_XL, student.getXl()));
            vo.setMajorName(major.getName());
            return JsonResult.ok().setData(vo);
        }
        return read(model.getId());
    }
    @Override
    @Transactional
    public JsonResult add(CivilServiceApplicationRecommendation model) {
        if (model == null) {
            throw new ParameterException("参数对象为空");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User curUser = (User) authentication.getPrincipal();
        QueryWrapper<CivilServiceApplicationRecommendation> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", curUser.getUserId());
        CivilServiceApplicationRecommendation tmp = baseMapper.selectOne(wrapper);
        model.setUserId(curUser.getUserId());
        model.setCollegeCode(curUser.getCollegeCode());
        Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("user_id", curUser.getUserId()));
        model.setDegree(student.getDegree());
        model.setXh(student.getXh());
        model.setXm(student.getXm());
        model.setUpdateTime(new Date());
        if(tmp == null){
            model.setStatus(RecommendationConstants.RECOMMENDATION_STATUS_INIT);
            model.setCreateTime(model.getUpdateTime());
            baseMapper.insert(model);
        }else {
            if(tmp.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_INIT)
                    || tmp.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_REJECT)){
                model.setId(tmp.getId());
                model.setCreateTime(tmp.getCreateTime());
                baseMapper.updateById(model);
            }else {
                return JsonResult.error("已有数据进入审核流程，请勿重复添加");
            }
        }
        return read(model.getId());
    }

    @Override
    public JsonResult saveUpdate(CivilServiceApplicationRecommendation model) {
        if (model == null) {
            throw new ParameterException("参数对象为空");
        }
        if (model.getId() == null) {
            throw new ParameterException("参数对象id为空");
        }
        CivilServiceApplicationRecommendation tmp = baseMapper.selectById(model.getId());
        if (tmp.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_INIT)
                || tmp.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_REJECT)) {
            model.setUpdateTime(new Date());
            baseMapper.updateById(model);
            return read(model.getId());
        }
        return JsonResult.error("当前审核状态不能修改");
    }

    @Override
    public JsonResult delete(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return JsonResult.error("未提供有效的 ID 列表");
        }
        // 调用 MyBatis-Plus 的批量删除方法
        int result = baseMapper.deleteBatchIds(ids);
        // 检查删除的记录数是否大于 0
        if (result > 0) {
            return JsonResult.ok("删除成功");
        } else {
            return JsonResult.error("删除失败");
        }
    }
    //add和submit，前用于添加数据库，后用于转换目前状态。毕竟保存不一定提交,所以这里默认add是保存吗
    @Override
    public JsonResult submit(Integer id) {//提交绕过前端，只需要前端传id即可
        if (id == null) {
            throw new ParameterException("参数对象id为空");
        }
        CivilServiceApplicationRecommendation model = baseMapper.selectById(id);
        //提交，要求状态为未提交或被打回
        if (Objects.equals(model.getStatus(), RecommendationConstants.RECOMMENDATION_STATUS_INIT) || Objects.equals(model.getStatus(), RecommendationConstants.RECOMMENDATION_STATUS_REJECT)) {
            //转状态为已提交待审核
            model.setStatus(RecommendationConstants.RECOMMENDATION_STATUS_SUBMIT);
            model.setUpdateTime(new Date());
            baseMapper.updateById(model);
            return JsonResult.ok("提交成功");
        }
        return JsonResult.ok("已提交,请勿重复提交");
    }

    @Override
    public JsonResult audit(RecommendationAuditParam param) {
        if (param == null) {
            throw new ParameterException("参数对象为空");
        }

        if (param.getId() == null) {
            throw new ParameterException("参数对象id为空");
        }
        CivilServiceApplicationRecommendation model = baseMapper.selectById(param.getId());
        //需要单独拿状态？不能直接get吗
        if (Objects.equals(model.getStatus(), RecommendationConstants.RECOMMENDATION_STATUS_INIT)) {
            throw new ParameterException("还未提交，不能审核");
        }

        if (Objects.equals(model.getStatus(), RecommendationConstants.RECOMMENDATION_STATUS_PASS)) {
            throw new ParameterException("已经审核通过，不能审核");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User curUser = (User) authentication.getPrincipal();
        model.setReviewUser(curUser.getUserId());
        model.setStatus(RecommendationConstants.RECOMMENDATION_STATUS_PASS);
        model.setReviewComment(param.getComment());
        model.setSchoolRecommendationTime(new Date());
        baseMapper.updateById(model);
        return JsonResult.ok("已完成审核操作");
    }

    @Override
    public JsonResult export(Integer id, HttpServletResponse response) throws IOException {
        CivilServiceApplicationRecommendationVo vo = (CivilServiceApplicationRecommendationVo) read(id).getData();
        String url = endpoint + "/" + MinioBucket.MINIO_RECMD + "/" + RecommendationConstants.Civil_App_Rec + "/" + vo.getUserId() + ".pdf";
        String path = recmdDir + File.separator + RecommendationConstants.Civil_App_Rec + File.separator + vo.getUserId() + ".pdf";
        if (!vo.getStatus().equals(RecommendationConstants.RECOMMENDATION_STATUS_PASS)) {
            return JsonResult.error("未通过审核，无法导出");
        }
        if (vo.getGenFlag().equals(RecommendationConstants.GEN_FLAG_NO)) {
            try {
                PdfWriter writer = new PdfWriter(new FileOutputStream(path));
                PdfDocument pdf = new PdfDocument(writer);
                Document document = new Document(pdf);
                addTableDocument(document, vo);
                document.close();
                writer.close();
                UpdateWrapper<CivilServiceApplicationRecommendation> wrapper = new UpdateWrapper<>();
                wrapper.eq("id", vo.getId()).set("gen_flag", RecommendationConstants.GEN_FLAG_YES)
                        .set("rpt_url", url);
                baseMapper.update(null, wrapper);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
                "attachment; filename=" + RecommendationConstants.Civil_App_Rec + ".pdf");
        File file = new File(path);
        byte[] fileBytes = Files.readAllBytes(file.toPath());
        try (OutputStream os = response.getOutputStream()) {
            os.write(fileBytes);
        }
        return JsonResult.ok(url);
    }

    private void addTableDocument(Document document, CivilServiceApplicationRecommendationVo vo) {
        try {
            String fontUrl = pdfFont + "simsun.ttc,1";
            PdfFont font = PdfFontFactory.createFont(
                    fontUrl,
                    PdfEncodings.IDENTITY_H,                 // 编码
                    PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED  // 嵌入策略

            );

            // 创建表格
            Table frontTable = new Table(UnitValue.createPercentArray(new float[]{7, 6, 6, 7,9, 7,6,6, 6, 6, 6,16}))//12
                    .setWidth(UnitValue.createPercentValue(100))
                    .setFont(font)
                    .setFontSize(10);
            //表头
            Cell title1 = new Cell(1, 12).add(new Paragraph("中央机关及其直属机构考试录用公务员")).setFontSize(25).setBold().setBorder(Border.NO_BORDER).setMinHeight(40).setTextAlignment(TextAlignment.CENTER);
            frontTable.addCell(title1);
            Cell title2 = new Cell(1, 12).add(new Paragraph("报名推荐表")).setFontSize(25).setBold().setBorder(Border.NO_BORDER).setMinHeight(40).setTextAlignment(TextAlignment.CENTER);
            frontTable.addCell(title2);
            Cell title3 = new Cell(1, 12).add(new Paragraph("（适用于普通高等院校应届毕业生）")).setFontSize(15).setBold().setBorder(Border.NO_BORDER).setMinHeight(40).setTextAlignment(TextAlignment.CENTER);
            frontTable.addCell(title3);
            Cell title4 = new Cell(1, 12).add(new Paragraph("毕业院校（系）："+vo.getCollegeName()+"               "+"身份证号:"+vo.getSfzhm())).setFontSize(10).setBorder(Border.NO_BORDER).setMinHeight(5).setTextAlignment(TextAlignment.CENTER);
            frontTable.addCell(title4);
            // 第一行:姓名、性别、民族、出生年月、照片
            frontTable.addCell(createCell("姓名", 1, 1));
            frontTable.addCell(createCell(vo.getXm(), 2, 1));
            frontTable.addCell(createCell("性别", 1, 1));
            frontTable.addCell(createCell(vo.getXb(), 1, 1));
            frontTable.addCell(createCell("民族", 1, 1));
            frontTable.addCell(createCell(vo.getMz(), 1, 1));
            frontTable.addCell(createCell("出生年月", 2, 1));
            Date csrq = vo.getCsrq(); // 获取日期
            SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = targetFormat.format(csrq);
            frontTable.addCell(createCell(formattedDate, 2, 1));
            Cell photoCell = new Cell(5, 1);// 照片区域
            if (vo.getPhotoUrl() != null) {
                ImageData photoData = ImageDataFactory.create(vo.getPhotoUrl());
                Image photo = new Image(photoData);
                photo.scaleToFit(100, 120);
                photo.setTextAlignment(TextAlignment.CENTER);
                photoCell.add(photo).setVerticalAlignment(VerticalAlignment.MIDDLE).setTextAlignment(TextAlignment.CENTER);
            }
            frontTable.addCell(photoCell);
            //第二行:籍贯、生源、婚否、政治面貌
            frontTable.addCell(createCell("籍贯", 1, 1));
            frontTable.addCell(createCell(StrUtil.isBlank(vo.getNativePlace()) ? "" : vo.getNativePlace(), 2, 1));
            frontTable.addCell(createCell("生源", 1, 1));
            frontTable.addCell(createCell(vo.getSyszd(), 1, 1));
            frontTable.addCell(createCell("婚否", 1, 1));
            frontTable.addCell(createCell(vo.getHyzk(), 1, 1));
            frontTable.addCell(createCell("政治面貌", 2, 1));
            frontTable.addCell(createCell(vo.getZzmm(), 2, 1));
            //第三行:所学专业及学位
            frontTable.addCell(createCell("所学专业及学位", 3, 1));
            frontTable.addCell(createCell(vo.getMajorDegree(), 8, 1));
            //第四行:爱好和特长
            frontTable.addCell(createCell("爱好和特长", 3, 1));
            frontTable.addCell(createCell(StrUtil.isBlank(vo.getHobbiesAndSkills()) ? "" : vo.getHobbiesAndSkills(), 8, 1));
            //第五行:在校曾任何种职务
            frontTable.addCell(createCell("在校曾任何种职务", 3, 1));
            frontTable.addCell(createCell(StrUtil.isBlank(vo.getPositionsHeld()) ? "" : vo.getPositionsHeld(), 8, 1));
            //第六行:奖惩情况
            frontTable.addCell(createCellVer("奖惩情况", 1, 4).setMinHeight(100).setVerticalAlignment(VerticalAlignment.MIDDLE));
            frontTable.addCell(createCell(StrUtil.isBlank(vo.getAwardsAndPunishments()) ? "" : vo.getAwardsAndPunishments(), 11, 4));
            //第七行:个人简历+家庭成员情况
            frontTable.addCell(createCellVer("个人简历 ", 1, 4).setMinHeight(100).setVerticalAlignment(VerticalAlignment.MIDDLE));
            frontTable.addCell(createCell(StrUtil.isBlank(vo.getResume()) ? "" : vo.getResume(), 5, 4));
            frontTable.addCell(createCellVer("家庭成员情况", 1, 4).setMinHeight(100).setVerticalAlignment(VerticalAlignment.MIDDLE));
            frontTable.addCell(createCell(StrUtil.isBlank(vo.getFamilyMembers()) ? "" : vo.getFamilyMembers(), 5, 4));
            //第七行:综合评价
            frontTable.addCell(createCellLeft("院、系党组织对学生在校期间德、智、体诸方面的综合评价：", 12, 1).setBorderBottom(Border.NO_BORDER));
            frontTable.addCell(createCell("", 12, 1).setMinHeight(130).setBorderBottom(Border.NO_BORDER).setBorderTop(Border.NO_BORDER));
            frontTable.addCell(createCell("", 6, 1).setMinHeight(20).setBorderTop(Border.NO_BORDER).setBorderBottom(Border.NO_BORDER).setBorderRight(Border.NO_BORDER));
            frontTable.addCell(createCell("院、系党总支签章  ", 6, 1).setBorderTop(Border.NO_BORDER).setBorderBottom(Border.NO_BORDER).setBorderLeft(Border.NO_BORDER));
            frontTable.addCell(createCell("负责人签字:", 6, 1).setBorderTop(Border.NO_BORDER).setBorderRight(Border.NO_BORDER));
            frontTable.addCell(createCell("年   月   日                                        ", 6, 1).setBorderTop(Border.NO_BORDER).setBorderLeft(Border.NO_BORDER));
            // 将表格添加到文档
            document.add(frontTable);
            //换页
            // 创建表格
            Table frontTable1 = new Table(UnitValue.createPercentArray(new float[]{15,9,9,15,9,9,15,9,9}))//9
                    .setWidth(UnitValue.createPercentValue(100))
                    .setFont(font)
                    .setFontSize(9);
            frontTable1.addCell(createCell("主要课程学习成绩",9,1));
            frontTable1.addCell(createCell("第一学年学习成绩",3,1));
            frontTable1.addCell(createCell("第二学年学习成绩",3,1));
            frontTable1.addCell(createCell("第三学年学习成绩",3,1));
            frontTable1.addCell(createCell("课程名称",1,1));
            frontTable1.addCell(createCell("上学期",1,1));
            frontTable1.addCell(createCell("下学期",1,1));
            frontTable1.addCell(createCell("课程名称",1,1));
            frontTable1.addCell(createCell("上学期",1,1));
            frontTable1.addCell(createCell("下学期",1,1));
            frontTable1.addCell(createCell("课程名称",1,1));
            frontTable1.addCell(createCell("上学期",1,1));
            frontTable1.addCell(createCell("下学期",1,1));
            for (int i = 1; i <= 9; i++) {
                for (int j = 1; j <= 9; j++) {
                    frontTable1.addCell(createCell(" ", 1, 1).setMinHeight(15));
                }
            }
            frontTable1.addCell(createCell(" ",6,1).setBorderRight(Border.NO_BORDER));
            frontTable1.addCell(createCell("教务处盖章",3,1).setBorderLeft(Border.NO_BORDER));
            frontTable1.addCell(createCellVer("院校毕分办意见", 1, 7).setMinHeight(100));
            frontTable1.addCell(createCell("同意！", 5, 6).setMinHeight(80).setBorderBottom(Border.NO_BORDER).setBorderRight(Border.NO_BORDER));
            SimpleDateFormat formatDate = new SimpleDateFormat("yyyy年MM月dd日");
            String schoolRecommendationDate = "无";
            Date schoolRecommendationTime = vo.getSchoolRecommendationTime();
            if (schoolRecommendationTime != null) {
                schoolRecommendationDate = formatDate.format(schoolRecommendationTime);
            }
            Cell schoolSealCell = createCell("院校毕分办签章" + "\n" + schoolRecommendationDate, 3, 7).setBorderTop(Border.NO_BORDER).setBorderBottom(Border.NO_BORDER).setBorderLeft(Border.NO_BORDER).setTextAlignment(TextAlignment.RIGHT).setVerticalAlignment(VerticalAlignment.BOTTOM);
            addSeal(schoolSealCell);
            frontTable1.addCell(schoolSealCell);
            frontTable1.addCell(createCell("负责人签字:温习", 5, 1).setMinHeight(20).setBorderBottom(Border.NO_BORDER).setBorderTop(Border.NO_BORDER).setBorderRight(Border.NO_BORDER));
            frontTable1.addCell(createCellVer("备注", 1, 1));
            frontTable1.addCell(createCell(" ", 8, 1).setMinHeight(40));
            frontTable1.addCell(createCellLeft("填表说明：\n" +
                    "            1.请填表人实事求是地填写，以免影响正常录用工作，未经毕分办签章此表无效。\n" +
                    "            2.“生源”指大学生上大学前户口所在的省、自治区、直辖市。\n" +
                    "            3.“奖惩情况”包括考生大学期间的各种奖励或惩处。学习期间，如获奖励，请学生处审核并将奖状或证书影印件加盖公章后附上。\n" +
                    "            4.填写本表“学习成绩”栏后，须盖教务处章。如有学生个人成绩登记单（表）可附复印件（加盖教务处章），免填此栏。",9,7).setBorder(Border.NO_BORDER));

            document.add(frontTable1);


            // 关闭文档
            document.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private Cell createCell(String content, int colSpan, int rowSpan) {
        Paragraph paragraph = new Paragraph(content)
                .setTextAlignment(TextAlignment.CENTER); // 在段落中设置对齐

        Cell cell = new Cell(rowSpan, colSpan)
                .add(paragraph)
                .setPadding(5);

        return cell;
    }

    private Cell createCellVer(String content, int colSpan, int rowSpan) {
        Paragraph paragraph = new Paragraph(content)
                .setTextAlignment(TextAlignment.CENTER)
                .setMaxWidth(10)
                .setHorizontalAlignment(HorizontalAlignment.CENTER)
                .setVerticalAlignment(VerticalAlignment.MIDDLE);

        Cell cell = new Cell(rowSpan, colSpan)
                .add(paragraph)
                .setPadding(5);

        return cell;
    }

    private Cell createCellLeft(String content, int colSpan, int rowSpan) {//设置了一个专门换行的文字填充方法，只针对长文字加入
        content = content.replaceAll("(\\w{60})", "$1\n");
        Paragraph paragraph = new Paragraph(content)
                .setTextAlignment(TextAlignment.LEFT); // 在段落中设置对齐

        Cell cell = new Cell(rowSpan, colSpan)
                .add(paragraph)
                .setPadding(5);
        return cell;
    }

    private void addSeal(Cell cell) {
        try {
            ImageData sealData = ImageDataFactory.create(pdfPicture + "careerGuidanceSeal.jpg");
            Image sealImage = new Image(sealData);

            BackgroundPosition backgroundPosition = new BackgroundPosition().setPositionX(BackgroundPosition.PositionX.CENTER).setPositionY(BackgroundPosition.PositionY.BOTTOM);
            BackgroundRepeat.BackgroundRepeatValue backgroundRepeatValue = BackgroundRepeat.BackgroundRepeatValue.NO_REPEAT;
            BackgroundRepeat backgroundRepeat = new BackgroundRepeat(backgroundRepeatValue, backgroundRepeatValue);
            BackgroundSize backgroundSize = new BackgroundSize();
            backgroundSize.setBackgroundSizeToValues(
                    UnitValue.createPointValue(Utilities.millimetersToPoints(35)),
                    UnitValue.createPointValue(Utilities.millimetersToPoints(35))
            );
            BackgroundImage backgroundImage = new BackgroundImage.Builder()
                    .setImage(sealImage.getXObject())  // 传递 Image 对象
                    .setBackgroundPosition(backgroundPosition)  // 图片居中
                    .setBackgroundRepeat(backgroundRepeat)  // 不重复平铺
                    .setBackgroundSize(backgroundSize)
                    .build();
            cell.setBackgroundImage(backgroundImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}